package vn.cuhanh.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import vn.cuhanh.ConfirmSharing;
import vn.cuhanh.LoginFacebookActivity;
import vn.cuhanh.R;
import vn.cuhanh.ShareActivity;
import vn.cuhanh.bean.ShareInfo;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;

public class ShareFacebook {
	private static final String TAG = "Share facebook";
	public static Context ctx; 
	private static ShareFacebook instance;
	public static String facebookName;
	public static String facebookUserName;
	public static String lastPostId = "";
	public static final List<String> PUBLISH_PERMISSIONS = Arrays.asList("publish_actions");
	
	private ShareFacebook(Context ctx) {
	}
	
	public static ShareFacebook getInstance(Context ctx) {
		ShareFacebook.ctx = ctx;
		if(instance == null) {
			instance = new ShareFacebook(ctx);
		}
		return instance;
	}
	
	private ProgressDialog progress;
	
	public void confirmSharingFacebook(final ShareInfo shareInfo) {
		if(facebookName != null && facebookUserName != null) {
			showConfirmSharingFacebookActivity(shareInfo);
			return;
		}
		progress = ProgressDialog.show(ctx, null, ctx.getResources().getString(R.string.share_progress_dialog_message));
		getFaceBookInfo(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(progress != null) {
					progress.dismiss();
				}
				showConfirmSharingFacebookActivity(shareInfo);
			}
		});
	}
	
	public void showConfirmSharingFacebookActivity(ShareInfo shareInfo) {
		Intent intent = new Intent(ctx, ConfirmSharing.class);
		intent.putExtra("vn.cuhanh.ConfirmSharing.name", shareInfo.getName());
		intent.putExtra("vn.cuhanh.ConfirmSharing.description", shareInfo.getDescription() + ShareActivity.getDownloadRef(ctx));
		intent.putExtra("vn.cuhanh.ConfirmSharing.imageUrl", shareInfo.getUrlImg());
		intent.putExtra("vn.cuhanh.ConfirmSharing.destination", ShareActivity.DESTINATION_FACEBOOK);
		intent.putExtra("vn.cuhanh.ConfirmSharing.userDisplayName", facebookName);
		intent.putExtra("vn.cuhanh.ConfirmSharing.userName", facebookUserName);
		((Activity)ctx).startActivityForResult(intent, ShareActivity.CONFIRM_SHARING_REQUEST_CODE);
	}
	
	public boolean getFaceBookInfo(final Runnable callBack) {
		Session session = Session.getActiveSession();
		if(session == null) {
	        session = new Session.Builder(ctx).build();
	        Session.setActiveSession(session);
			facebookRequestLogin();
			return false;
		}
		Request.executeMeRequestAsync(session, new GraphUserCallback() {
			
			@Override
			public void onCompleted(GraphUser user, Response response) {
				// TODO Auto-generated method stub
				try {
					facebookName = user.getName();
					facebookUserName = user.getUsername();
					Log.d(TAG, String.valueOf(user.getName()));
					if(callBack != null) {
						callBack.run();
					}
				} catch (Exception e) {
					HelperFunc.readStackTrace(e);
				}
			}
		});
		return true;
	}

	
	public void facebookRequestLogin() {
		LoginFacebookActivity.clickLoginAlready = false;
		Intent intent = new Intent(ctx, LoginFacebookActivity.class);
		((Activity)ctx).startActivityForResult(intent, ShareActivity.FACEBOOK_LOGIN_REQUEST_CODE);
//		LoginButton btnLoginFacebook = (LoginButton)findViewById(R.id.facebook_login_button);
//		btnLoginFacebook.performClick();
	}
	
	public void publishStory(final ShareInfo shareInfo, final Runnable successCallback, final Runnable failCallback) {
	    Session session = Session.getActiveSession();

	    if (session != null){

	        // Check for publish permissions    
	        List<String> permissions = session.getPermissions();
	        if (!isSubsetOf(PUBLISH_PERMISSIONS, permissions)) {
	            Session.NewPermissionsRequest newPermissionsRequest = new Session
	                    .NewPermissionsRequest(((Activity)ctx), PUBLISH_PERMISSIONS);
	            
	            session.requestNewPublishPermissions(newPermissionsRequest);
	            return;
	        }

	        Bundle postParams = new Bundle();
	        postParams.putString("name", shareInfo.getName());
	        postParams.putString("caption", shareInfo.getTitle());
	        postParams.putString("description", shareInfo.getDescription() + ShareActivity.getDownloadRef(ctx));
	        postParams.putString("link", shareInfo.getLink());
	        postParams.putString("picture", shareInfo.getUrlImg());

	        Request.Callback callback = new Request.Callback() {
	            public void onCompleted(Response response) {
	            	lastPostId = "";
	                try {
	                	JSONObject graphResponse = response
	                			.getGraphObject()
	                			.getInnerJSONObject();
	                	lastPostId = graphResponse.getString("id");
	                } catch (JSONException e) {
	                    Log.i(TAG,
	                        "JSON error " + e.getMessage());
	                    Toast.makeText(ctx,
		                         ctx.getResources().getString(R.string.unknown_error),
		                         Toast.LENGTH_SHORT).show();
	                } catch (NullPointerException e) {
						// TODO: handle exception
//	                	Toast.makeText(ShareActivity.this,
//		                         getResources().getString(R.string.unknown_error),
//		                         Toast.LENGTH_SHORT).show();
					}
	                FacebookRequestError error = response.getError();
	                if (error != null) {
	                	if(error.getErrorCode() == FacebookRequestError.INVALID_HTTP_STATUS_CODE) {
	                		HelperFunc. showAlertDialogOnUiThread(ctx, ctx.getResources().getString(R.string.shareFailTitle), 
	                				ctx.getResources().getString(R.string.no_network_2));
	                	} else {
	                		HelperFunc.showAlertDialogOnUiThread(ctx, ctx.getResources().getString(R.string.shareFailTitle), 
	                				ctx.getResources().getString(R.string.unknown_error));
	                	}
	                	Log.d(TAG, error.getErrorMessage());
	                	if(failCallback != null) {
	                		failCallback.run();
	                	}
                    } else {
                    	if(successCallback != null) {
                    		successCallback.run();
                    	}
	                }
	            }
	        };

	        Request request = new Request(session, "me/feed", postParams, 
	                              HttpMethod.POST, callback);

	        RequestAsyncTask task = new RequestAsyncTask(request);
	        task.execute();
	    } else {
	    	
	    }
	}
	
	private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
	    for (String string : subset) {
	        if (!superset.contains(string)) {
	            return false;
	        }
	    }
	    return true;
	}
}
